package com.reeygu.item.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.Date;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.reeygu.item.pojo.User;
import com.reeygu.item.vo.RespBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 做压力测 自动生成测试数据
 */
public class UserAutoGeneral {
    private static final int USER_NUM = 100;

    public static void main(String[] args) throws Exception{
        creatUserInfoFile(creatUserInfo());
    }
    //数据库生成用户数据
    public static List<User> creatUserInfo() throws Exception{
        List<User> users = new ArrayList<>();
        for (int i = 0; i < USER_NUM; i++) {
            Random random = new Random();
            StringBuilder buffer = new StringBuilder();
            for (int j = 0; j < 8; j++) {
                buffer.append(random.nextInt(10));
            }
            String phoneLastNum = buffer.toString();
            String salt = phoneLastNum.substring(0, 8);
            User user = new User();
            user.setId(Long.parseLong("130" + phoneLastNum));
            user.setNickname("user" + i);
            user.setPassword(MD5Util.getPassFromUpdatePass(MD5Util.getPassFromFrontPass(salt), salt));
            user.setSlat(salt);
            user.setHead("");
            user.setRegisterDate(new Date());
            user.setUpdateDate(new Date());
            user.setLastLoginDate(new Date());
            user.setLoginCount(1);
            user.setBeforeLoginIp("127.0.0.1");
            users.add(user);
        }
        Connection connection = getConnect();
        String sql = "insert into t_user(id, nickname, password, slat, register_date) " +
                "VALUES (?, ?, ?, ?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (User u : users) {
            preparedStatement.setLong(1, u.getId());
            preparedStatement.setString(2, u.getNickname());
            preparedStatement.setString(3, u.getPassword());
            preparedStatement.setString(4, u.getSlat());
            preparedStatement.setTimestamp(5, new Timestamp(new Date().getTime()));
            preparedStatement.addBatch();
        }
        preparedStatement.executeBatch();
        preparedStatement.clearParameters();
        preparedStatement.close();
        connection.close();
        //生成测试文件数据
        System.out.println("数据库操作完成");
        return users;
    }

    public static void creatUserInfoFile(List<User> users) throws Exception {
        // 定义请求的URL和本地文件路径
        String urlString = "http://localhost:8080/login/doLogin";
        String fileUrl = "E:\\Desktop\\config.txt";

        // 创建本地文件对象并检查是否存在，如果存在则删除
        File file = new File(fileUrl);
        if (file.exists()) {
            file.delete();
        }

        // 创建随机访问文件对象，以便在文件末尾写入数据
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        randomAccessFile.seek(0);  // 设置文件指针位置为文件开头
        // 创建URL对象
        URL url = new URL(urlString);
        // 遍历用户列表
        for (User u : users) {


            // 打开HTTP连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");  // 设置请求方法为POST
            httpURLConnection.setDoOutput(true);  // 允许写入请求数据

            // 获取输出流，将请求参数写入流中
            OutputStream outputStream = httpURLConnection.getOutputStream();
            String params = "mobile=" + u.getId() + "&password=" + MD5Util.getPassFromFrontPass(u.getSlat());
            outputStream.write(params.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();

            // 获取服务器响应流
            InputStream inputStream = httpURLConnection.getInputStream();

            // 读取响应数据并转化为字符串
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  // 创建一个字节输出流对象
            byte[] buff = new byte[1024];  // 创建一个字节数组作为缓冲区
            int len = 0;  // 用于存储每次读取的字节数
            // 通过循环，从输入流中读取数据，并将其写入字节输出流中
            while ((len = inputStream.read(buff)) >= 0) {
                baos.write(buff, 0, len);  // 将缓冲区的数据写入字节输出流
            }
            inputStream.close();  // 关闭输入流
            baos.close();  // 关闭字节输出流
            // 将字节输出流中的字节数据转换为字符串
            String response = new String(baos.toByteArray());


            // 使用ObjectMapper将响应数据映射为RespBean对象
            ObjectMapper mapper = new ObjectMapper();
            RespBean respBean = mapper.readValue(response, RespBean.class);

            // 获取用户凭证
            String userTicket = (String) respBean.getObj();

            // 在控制台输出用户凭证相关信息
            System.out.println("create userTicket:" + u.getId());

            // 构建要写入文件的数据行，并将其写入文件末尾
            String row = u.getId() + "," + userTicket;
            randomAccessFile.seek(randomAccessFile.length());  // 设置文件指针位置为文件末尾
            randomAccessFile.write(row.getBytes(StandardCharsets.UTF_8));
            randomAccessFile.write("\r\n".getBytes(StandardCharsets.UTF_8));  // 换行
            System.out.println("write to file :" + u.getId());
        }

        // 关闭随机访问文件对象
        randomAccessFile.close();

        // 输出文件写入完成信息
        System.out.println("file write is over");
    }


    //连接池
    public static Connection getConnect() throws Exception{
        String url = "jdbc:mysql://localhost:3306/concurrency?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String driver = "com.mysql.cj.jdbc.Driver";
        String password = "881911";
        String username = "root";
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }
}
